<script setup>
import { ref } from 'vue'
import { useArticleCateStore } from '@/stores/articleCate.js'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { addArticle, editArticle, getArticleDetail } from '@/api/article.js'
import { fileServer } from '@/utils/request.js'
import axios from 'axios'
const visibleDrawer = ref(false);
const articleCateStore = useArticleCateStore()
const type = ref()
const data = ref({
  title: '',
  cate_name: '',
  cover_img: '',
  content: '',
  state: ''
})
// 给父组件发消息，让其重新获取列表
const emit = defineEmits(['flush'])

const imgUrl = ref()
const onSelectFile = (file) => {
  // 将二进制文件转为浏览器可识别的url
  imgUrl.value = URL.createObjectURL(file.raw)
  // 注意，这里是直接穿二进制进去
  data.value.cover_img = file.raw
}
const open = async (id) => {
  visibleDrawer.value = true

  if (id) {
    type.value = 'edit'
    // 编辑，数据回显，从后端拿数据。
    const res =  await getArticleDetail(id)
    data.value = res.data.data
    // 此步结束后，图片可以正常回显（从后端拿数据）
      // "cover_img": "/uploads/80ebef4fbdf69cf9eef05c26057c6dcc.jpg"
      // :src会拼接上我们的baseURL，这个baseURL是我们图片服务器的地址
    imgUrl.value = fileServer + data.value.cover_img
    // 需要将cover_img化为file二进制文件的形式。才能进行上传
    data.value.cover_img = await imageUrlToFile(imgUrl.value, data.value.cover_img)
  }
  else {
    type.value = 'add'
    console.log('添加')
  }
}
defineExpose({
  open
})

// 将网络图片地址转换为File对象(这个函数直接上网搜)
async function imageUrlToFile(url, fileName) {
  try {
    // 第一步：使用axios获取网络图片数据
    const response = await axios.get(url, { responseType: 'arraybuffer' });
    const imageData = response.data;

    // 第二步：将图片数据转换为Blob对象
    const blob = new Blob([imageData], { type: response.headers['content-type'] });

    // 第三步：创建一个新的File对象
    const file = new File([blob], fileName, { type: blob.type });

    return file;
  } catch (error) {
    console.error('将图片转换为File对象时发生错误:', error);
    throw error;
  }
}

const submitBtn = async (state) => {
  data.value.state = state
  // 发送表单数据
  const fd = new FormData()
  for (let key in data.value) {
    fd.append(key, data.value[key])
  }
  await addArticle(fd)

  ElMessage.success('提交成功')
  visibleDrawer.value = false
  emit('flush')
}

const updateArticle = async () => {
  const fd = new FormData()
  for (let key in data.value) {
    fd.append(key, data.value[key])
  }
  await editArticle(fd)
  ElMessage.success('编辑成功')
  visibleDrawer.value = false
  emit('flush')
}
</script>

<template>
  <el-drawer
    v-model="visibleDrawer"
    title="新增文章"
    size="40%"
  >
    <el-form>
      <el-form-item label="文字标题：">
        <el-input v-model="data.title"></el-input>
      </el-form-item>
      <el-form-item label="文章分类：">
        <el-select placeholder="请选择" clearable v-model="data.cate_id" >
          <el-option v-for="item in articleCateStore.cateList"  :key="item.id" :label="item.cate_name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="文章封面：" prop="cover_img">
        <el-upload class="avatar-uploader" :show-file-list="false" :auto-upload="false" :on-change="onSelectFile">
          <!--如果imgUrl存在，则显示这个照片，否则显示＋号-->
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容：" prop="content">
        <div class="editor">
          <quill-editor
            theme="snow"
            v-model:content="data.content"
            contentType="html"
          >
          </quill-editor>
        </div>
      </el-form-item>
      <el-form-item v-if="type === 'add'">
        <el-button type="primary" @click="submitBtn('已发布')">发布</el-button>
        <el-button type="info" @click="submitBtn('草稿')">草稿</el-button>
      </el-form-item>
      <el-form-item v-if="type === 'edit'">
        <el-button type="primary" @click="updateArticle">更新</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style scoped lang="scss">
.el-select {
  --el-select-width: 100%;
}
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
